package eu.webmedia.recruitment.comics.preferences;

import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import eu.webmedia.recruitment.comics.user.User;

@Repository
public class PreferenceServiceJdbcImpl implements PreferenceService {
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	

	@Override
	public Preferences findByUser(User user) {
		List<String> stripNames = jdbcTemplate.
				queryForList("SELECT strip_name FROM preference WHERE username = ?", 
					String.class, user.getUsername());
		
		return new Preferences(stripNames);
	}


	@Override
	public void save(Preferences newPreferences, User user) {
		Preferences existing = findByUser(user);
		
		Collection<String> deleted = existing.getDeleted(newPreferences);
		delete(deleted, user);
		
		Collection<String> added = existing.getAdded(newPreferences);
		add(added, user);
	}
	
	private void delete(Collection<String> deleted, User user) {
		for (String stripName : deleted) {
			jdbcTemplate.update("DELETE FROM preference WHERE username = ? AND strip_name = ?",
					user.getUsername(), stripName);
		}
	}
	
	private void add(Collection<String> added, User user) {
		for (String stripName : added) {
			jdbcTemplate.update("INSERT INTO preference(username, strip_name) VALUES(?, ?)",
					user.getUsername(), stripName);
		}
	}

}
